angular.module('mvcApp.shop-admin', [
    'ngRoute',
    'ngResource'
]).config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/shop-admin/category', {
            templateUrl: 'static/views/shop-admin.html',
            controller: 'ShopAdminCtrl'
        })
        .when('/shop-admin/shop/:shopId', {
            templateUrl: 'static/views/shop-admin.html',
            controller: 'ShopAdminCtrl'
        })
        .when('/shop-admin/create_shop/:create', {
            templateUrl: 'static/views/shop-admin.html',
            controller: 'ShopAdminCtrl'
        })
        .when('/shop-admin/category/:categoryId', {
            templateUrl: 'static/views/shop-admin.html',
            controller: 'ShopAdminCtrl'
        });
}]).controller('ShopAdminCtrl', ['$scope', '$routeParams', '$http', 'Shop', 'Category', 'Product', 'User',
    function($scope, $routeParams, $http, Shop, Category, Product, User) {
        $scope.shops = [];
        $scope.categoryId = $routeParams.categoryId || '';
        $scope.page = 1;
        $scope.pageSize = 10;
        $scope.total = 0;
        $scope.currentPage = 'list';
        $scope.shopCategories = [];
        if ($routeParams.shopId) {
            $scope.shopId = $routeParams.shopId;
            Shop.getShop($routeParams.shopId)
                .then(function (shop) {
                    $scope.currentShop = shop;
                    $scope.toShowProductsOfShop(shop);
                }).catch(function (err) {
                    if (err) {
                        alert(err);
                    }
                });
        }

        Category.listShopCategories()
            .then(function(data) {
                $scope.shopCategories = data;
                $scope.$apply();
            }).catch(function(err) {
                console.log('list shop categories error', err);
            });
        $scope.loadShops = function() {
            Shop.listShops($scope.categoryId, $scope.page)
                .then(function(data) {
                    $scope.shops = data.records;
                    $scope.total = data.total;
                    $scope.$apply();
                }).catch(function(err) {
                    alert(err);
                });
        };
        $scope.loadShops();
        $scope.toCreateShop = function() {
            $scope.currentPage = 'create';
        };
        $scope.toCreateProduct = function() {
            $scope.currentPage = 'create_product';
        };
        $scope.toShowShops = function() {
            $scope.currentPage = 'list';
        };
        if($scope.currentPage==='create') {
            setTimeout(function() {
                if($(".edui-editor").length<1) {
                    window.location.reload();
                }
            }, 2500);
        }
        $scope.currentShop = null;
        $scope.productsOfCurrentShop = [];
        $scope.loadProductsOfCurrentShop = function() {
            Product.listProducts($scope.currentShop.id, 1, 100)
                .then(function(records) {
                    $scope.productsOfCurrentShop = records;
                    $scope.$apply();
                }).catch(function(err) {
                    console.log(err);
                });
        };
        $scope.shopCommentsPage = 1;
        $scope.shopCommentsPageSize = 20;
        $scope.shopComments = [];
        $scope.shopCommentsTotal = 0;
        $scope.productCommentsPage = 1;
        $scope.productCommentsPageSize = 20;
        $scope.productComments = [];
        $scope.productCommentsTotal = 0;
        $scope.loadCommentsOfCurrentShop = function() {
            if($scope.shopCommentsPage < 1) {
                $scope.shopCommentsPage = 1;
            }
            Shop.listShopComments($scope.currentShop.id, $scope.shopCommentsPage, $scope.shopCommentsPageSize)
                .then(function(data) {
                    $scope.shopComments = data.records;
                    $scope.shopCommentsTotal = data.total;
                    _.each($scope.shopComments, function(comment) {
                        User.getUserInfoWithCache(comment.userId)
                            .then(function(userInfo) {
                                comment.user = userInfo;
                                $scope.$apply();
                            }).catch(function(err) {
                                console.log(err);
                            });
                    });
                    $scope.$applyAsync();
                }).catch(function(err) {
                    console.log(err);
                });
        };
        $scope.loadCommentsOfCurrentProduct = function() {
            if($scope.productCommentsPage < 1) {
                $scope.productCommentsPage = 1;
            }
            Product.listProductComments($scope.currentProduct.id, $scope.productCommentsPage, $scope.productCommentsPageSize)
                .then(function(data) {
                    $scope.productComments = data.records;
                    $scope.productCommentsTotal = data.total;
                    _.each($scope.productComments, function(comment) {
                        User.getUserInfoWithCache(comment.userId)
                            .then(function(userInfo) {
                                comment.user = userInfo;
                                $scope.$apply();
                            }).catch(function(err) {
                                console.log(err);
                            });
                    });
                    $scope.$applyAsync();
                }).catch(function(err) {
                    console.log(err);
                });
        };
        $scope.showPrevShopComments = function() {
            $scope.shopCommentsPage -= 1;
            $scope.loadCommentsOfCurrentShop();
        };
        $scope.showNextShopComments = function() {
            $scope.shopCommentsPage += 1;
            $scope.loadCommentsOfCurrentShop();
        };
        $scope.shopCommentsPagesCount = function() {
            return 1 + parseInt(($scope.shopCommentsTotal - 1) / $scope.shopCommentsPageSize);
        };
        $scope.showPrevProductComments = function() {
            $scope.productCommentsPage -= 1;
            $scope.loadCommentsOfCurrentProduct();
        };
        $scope.showNextProductComments = function() {
            $scope.productCommentsPage += 1;
            $scope.loadCommentsOfCurrentProduct();
        };
        $scope.productCommentsPagesCount = function() {
            return 1 + parseInt(($scope.productCommentsTotal - 1) / $scope.productCommentsPageSize);
        };
        $scope.selectedShopComments = [];
        $scope.selectAllCurrentShopComments = function() {
            $scope.selectedShopComments = _.map($scope.shopComments, function(c) {return c.id;});
        };
        $scope.deleteSelectedShopComments = function() {
            if($scope.selectedShopComments.length<1){
                return;
            }
            if(!window.confirm('确认删除选中的'+$scope.selectedShopComments.length+"条评论?")) {
                return;
            }
            Shop.deleteShopComments($scope.selectedShopComments)
                .then(function(){
                    $scope.loadCommentsOfCurrentShop();
                });
        };
        $scope.deleteShopComment = function(comment) {
            if(!window.confirm('确认删除此评论?')) {
                return;
            }
            Shop.deleteShopComments([comment.id])
                .then(function(){
                    $scope.loadCommentsOfCurrentShop();
                });
        };

        $scope.selectedProductComments = [];
        $scope.selectAllCurrentProductComments = function() {
            $scope.selectedProductComments = _.map($scope.productComments, function(c) {return c.id;});
        };
        $scope.deleteSelectedProductComments = function() {
            if($scope.selectedProductComments.length<1){
                return;
            }
            if(!window.confirm('确认删除选中的'+$scope.selectedProductComments.length+"条评论?")) {
                return;
            }
            Product.deleteComments($scope.selectedProductComments)
                .then(function(){
                    $scope.loadCommentsOfCurrentProduct();
                });
        };
        $scope.deleteProductComment = function(comment) {
            if(!window.confirm('确认删除此评论?')) {
                return;
            }
            Product.deleteComments([comment.id])
                .then(function(){
                    $scope.loadCommentsOfCurrentProduct();
                });
        };
        
        $scope.toShowProductsOfShop = function(shop) {
            $scope.currentShop = shop;
            $scope.currentPage = 'products_of_shop';
            $scope.loadProductsOfCurrentShop();
        };
        $scope.toManageShopComments = function(shop) {
            $scope.currentPage = 'comments_of_shop';
            $scope.currentShop = shop;
            $scope.loadCommentsOfCurrentShop();
        };
        $scope.toManageProductComments = function(product) {
            $scope.currentPage = 'comments_of_product';
            $scope.loadCommentsOfCurrentProduct();
        };
        $scope.feedbacks = [];
        $scope.feedbacksPage = 1;
        $scope.feedbacksTotal = 0;
        $scope.loadFeedbacksOfCurrentShop = function() {
            if($scope.feedbacksPage < 1) {
                $scope.feedbacksPage = 1;
            }
            Shop.getShopFeedbacks($scope.currentShop.id, $scope.feedbacksPage, $scope.pageSize)
                .then(function(feedbacks, total) {
                    $scope.feedbacks = feedbacks;
                    $scope.feedbacksTotal = total;
                    _.each($scope.feedbacks, function(feedback) {
                        User.getUserInfoWithCache(feedback.userId)
                            .then(function(userInfo) {
                                feedback.user = userInfo;
                                $scope.$apply();
                            }).catch(function(err) {
                                console.log(err);
                            });
                    });
                    $scope.$apply();
                }).catch(function(err) {
                    console.log(err);
                });
        };
        $scope.toViewShopFeedbacks = function(shop) {
            $scope.currentShop = shop;
            $scope.currentPage = 'feedbacks';
            $scope.loadFeedbacksOfCurrentShop();
        };
        $scope.toEditShop = function(shop) {
            $scope.currentShop = shop;
            $scope.currentPage = 'edit_shop';
        };
        $scope.updateShop = _.throttle(function(shop) {
            Shop.updateShop(shop.id, shop)
                .then(function() {
                    alert("已提交修改等待审核");
                    $scope.toShowShops();
                    $scope.loadShops();
                }).catch(function(err) {
                    alert(err);
                });
        }, 2500);
        $scope.newShopCategoryId = $scope.categoryId;
        $scope.createShop = _.throttle(function (name, description, categoryId, logoUrl, contact, address, newShopDiscount) {
            if(!name) {
                alert("请填入商户名称");
                return;
            }
            Shop.createShop(name, description, categoryId, logoUrl, contact, address, newShopDiscount)
                .then(function(shop) {
                    alert("添加商户已提交审核");
                    $scope.loadShops();
                    $scope.toShowShops();
                }).catch(function(err) {
                    alert(err);
                });
        }, 2500);
        $scope.createProduct = _.throttle(function (name, description, price, discount, logoUrl) {
            if(!name) {
                alert("请填入商品名称");
                return;
            }
            Product.createProduct(name, description, price, discount, $scope.currentShop.id, logoUrl)
                .then(function(product) {
                    alert("添加商品已提交审核");
                    $scope.toShowProductsOfShop($scope.currentShop);
                }).catch(function(err) {
                    alert(err);
                });
        }, 2500);
        
        $scope.toEditProduct = function(product) {
            $scope.currentProduct = product;
            $scope.currentPage = 'edit_product';
        };
        $scope.updateProductInfo = _.throttle(function(product) {
            Product.updateProduct(product.id, product)
                .then(function() {
                    alert("商品信息修改已提交审核");
                    $scope.toShowProductsOfShop($scope.currentShop);
                    $scope.loadProductsOfCurrentShop();
                }).catch(function(err) {
                    alert(err);
                });
        }, 2500);
        
        $scope.onUploadedShopAvatar = function(fileId) {
            var url = '/wechatshop/file/view_direct/' + encodeURIComponent(fileId);
            if($scope.currentPage === 'edit_shop') {
                $scope.currentShop.logoUrl = url;
            } else {
                $scope.newShopLogoUrl = url;
            }
            $scope.$apply();
        };
        $scope.onUploadedProductAvatar = function(fileId) {
            var url =  '/wechatshop/file/view_direct/' + encodeURIComponent(fileId);
            if($scope.currentPage === 'edit_product') {
                $scope.currentProduct.logoUrl = url;
            } else {
                $scope.newProductLogoUrl = url;
            }
            $scope.$apply();
        };

        if ($routeParams.create) {
            $scope.toCreateShop();
        }
    }]);